"""
销售线索服务类
"""
from app.models.customer import Lead, LeadFollowUp, LeadLog
from app import db


class LeadService:
    """销售线索服务类"""
    
    @staticmethod
    def get_lead_stats(manager_id):
        """获取销售线索统计数据"""
        try:
            from flask_login import current_user
            
            # 检查当前用户是否为系统管理员
            is_admin = getattr(current_user, 'role', None) == 'admin'
            
            # 根据用户角色决定查询范围
            if is_admin:
                # 系统管理员可以看到所有线索
                total = Lead.query.count()
                
                # 按状态统计
                new_count = Lead.query.filter_by(status='新线索').count()
                contacted_count = Lead.query.filter_by(status='已触达').count()
                qualified_count = Lead.query.filter_by(status='跟进中').count()
                converted_count = Lead.query.filter_by(status='已转化').count()
                lost_count = Lead.query.filter_by(status='已关闭').count()
            else:
                # 普通用户只能看到自己的线索
                total = Lead.query.filter_by(assigned_to=manager_id).count()
                
                # 按状态统计
                new_count = Lead.query.filter_by(assigned_to=manager_id, status='新线索').count()
                contacted_count = Lead.query.filter_by(assigned_to=manager_id, status='已触达').count()
                qualified_count = Lead.query.filter_by(assigned_to=manager_id, status='跟进中').count()
                converted_count = Lead.query.filter_by(assigned_to=manager_id, status='已转化').count()
                lost_count = Lead.query.filter_by(assigned_to=manager_id, status='已关闭').count()
            
            # 创建一个简单的对象来存储统计数据
            class Stats:
                def __init__(self, total, new, following, converted, closed):
                    self.total = total
                    self.new = new
                    self.following = following
                    self.converted = converted
                    self.closed = closed
            
            return Stats(total, new_count, qualified_count, converted_count, lost_count)
        except Exception as e:
            # 返回默认统计数据，避免模板错误
            class Stats:
                def __init__(self, total, new, following, converted, closed):
                    self.total = total
                    self.new = new
                    self.following = following
                    self.converted = converted
                    self.closed = closed
            
            return Stats(0, 0, 0, 0, 0)
    
    @staticmethod
    def get_lead_pool_stats(manager_id):
        """获取线索池统计数据"""
        try:
            from flask_login import current_user
            
            # 检查当前用户是否为系统管理员
            is_admin = getattr(current_user, 'role', None) == 'admin'
            
            # 线索池中的线索（未被分配的）
            if is_admin:
                # 系统管理员可以看到所有未分配的线索
                unassigned = Lead.query.filter_by(assigned_to=None).count()
                
                # 今日新增的线索
                from datetime import date
                today = date.today()
                today_new = Lead.query.filter_by(assigned_to=None).filter(
                    Lead.created_at >= today
                ).count()
                
                # 高优先级线索
                high_priority = Lead.query.filter_by(assigned_to=None, priority='高').count()
                
                # 待分配3天以上的线索
                from datetime import timedelta
                three_days_ago = today - timedelta(days=3)
                old_leads = Lead.query.filter_by(assigned_to=None).filter(
                    Lead.created_at < three_days_ago
                ).count()
            else:
                # 普通用户只能看到自己负责的未分配线索
                unassigned = Lead.query.filter_by(created_by=manager_id, assigned_to=None).count()
                
                # 今日新增的线索
                from datetime import date
                today = date.today()
                today_new = Lead.query.filter_by(created_by=manager_id, assigned_to=None).filter(
                    Lead.created_at >= today
                ).count()
                
                # 高优先级线索
                high_priority = Lead.query.filter_by(created_by=manager_id, assigned_to=None, priority='高').count()
                
                # 待分配3天以上的线索
                from datetime import timedelta
                three_days_ago = today - timedelta(days=3)
                old_leads = Lead.query.filter_by(created_by=manager_id, assigned_to=None).filter(
                    Lead.created_at < three_days_ago
                ).count()
            
            # 创建一个简单的对象来存储统计数据
            class PoolStats:
                def __init__(self, unassigned, today_new, high_priority, old_leads):
                    self.unassigned = unassigned
                    self.today_new = today_new
                    self.high_priority = high_priority
                    self.old_leads = old_leads
                    self.total = unassigned  # 添加total属性，等于未分配线索数
            
            return PoolStats(unassigned, today_new, high_priority, old_leads)
        except Exception as e:
            # 返回默认统计数据，避免模板错误
            class PoolStats:
                def __init__(self, unassigned=0, today_new=0, high_priority=0, old_leads=0):
                    self.unassigned = unassigned
                    self.today_new = today_new
                    self.high_priority = high_priority
                    self.old_leads = old_leads
                    self.total = unassigned
            
            return PoolStats(0, 0, 0, 0)